<template>
  <div class="radar">

    <!--S顶部-->
    <roof title="摊位雷达" :show-left-capsule="true"></roof>
    <!--E顶部-->

    <!--S内容-->
    <div id="content" :style="{'padding-top':content_padding_top+'px'}">

      <!--S分类选择-->
      <div id="classify">
        <scroll-view
          class="classify-scroll"
          :scroll-x="true">
            <div class="item active">
              <img src="https://file.geekdm.com/icon-2.png" />
              <p>美食</p>
            </div>
            <div class="item">
              <img src="https://file.geekdm.com/icon-2.png" />
              <p>美食</p>
            </div>
            <div class="item">
              <img src="https://file.geekdm.com/icon-2.png" />
              <p>美食</p>
            </div>
            <div class="item">
              <img src="https://file.geekdm.com/icon-2.png" />
              <p>美食</p>
            </div>
            <div class="item">
              <img src="https://file.geekdm.com/icon-2.png" />
              <p>美食</p>
            </div>
            <div class="item">
              <img src="https://file.geekdm.com/icon-2.png" />
              <p>美食</p>
            </div>
            <div class="item">
              <img src="https://file.geekdm.com/icon-2.png" />
              <p>美食</p>
            </div>
            <div class="item">
              <img src="https://file.geekdm.com/icon-2.png" />
              <p>美食</p>
            </div>
            <div class="item">
              <img src="https://file.geekdm.com/icon-2.png" />
              <p>美食</p>
            </div>
            <div class="item">
              <img src="https://file.geekdm.com/icon-2.png" />
              <p>美食</p>
            </div>
        </scroll-view>
      </div>
      <!--E分类选择-->

      <!--S地图-->
      <div id="map" :style="{height:map_height+'px'}">
        <!--S地图组件-->
          <map
            class="map"
            :longitude="map.lng"
            :latitude="map.lat"
            :scale="17"
            :show-location="true"
            :enable-traffic="true"
            :markers="stall_markers"
            :polyline="polyline"
            @markertap="clickMarker"
            >
          </map>
        <!--E地图组件-->

        <!--S搜索-->
        <div class="search">
          <input
            type="text"
            placeholder="想找什么搜一下"
            confirm-type="search"
            @confirm="sendSearch"
          />
        </div>
        <!--E搜索-->

        <!--S定位-->
        <div class="location">
          <i class="iconfont icon-dingwei"></i>
        </div>
        <!--E定位-->

        <!--S门店地图卡片信息-->
        <div class="card" v-if="marker_index >= 0">
          <div class="name">{{data[marker_index].name}}</div>
          <div class="time">营业时间：09:00-21:00</div>
          <div class="navigation-button" @click="showLine">
            <i class="iconfont icon-daohang"></i>
            <span>去这里</span>
          </div>
          <div class="address"><i class="iconfont icon-weizhidingwei"></i>门店地址门店地址</div>
          <div class="scope">
            <p>烧烤</p><p>烤全羊</p><p>烧烤</p><p>烤全羊</p><p>烧烤</p>
          </div>
        </div>
        <!--E门店地图卡片信息-->

      </div>
      <!--E地图-->

    <!--E内容-->
    </div>
    <!--E内容-->

    <!--Scanvas-->
    <canvas
      id="canvas"
      type="2d"
      ></canvas>
    <!--Ecanvas-->
  </div>
</template>

<script>
  import store from '../../store/index'
  import roof from '../../components/roof/Roof'
  import {select} from '../../utils/index'
  import File from '../../utils/file'
  import QQMapWX from '../../utils/qqmap-wx-jssdk.min'
  let QQMap
  export default {
    data () {
      return {
        // 顶部填充区域高度
        content_padding_top: 0,
        // 地图高度
        map_height: 0,
        canvas: null,
        context: null,
        // 地图
        map: {
          lng: 0,
          lat: 0
        },
        // 路线
        polyline: [],
        // 数据
        data: [
          {
            id: 1,
            icon: 'https://thirdwx.qlogo.cn/mmopen/0oVSEE3I8Jom2a4YJlSrGE0KyxOdlOJ4icPM3nVFhzric3AicWpIicBswah5juKVdbzpET2yTDRVjpSP1261vfict1ZcR3eB0mLdR/132',
            lat: '36.076401',
            lng: '111.577320',
            name: '门店名称1',
            time: '早10:00 - 晚11:00',
            address: '门店地址门店地址门店地址',
            scope: ['烧烤', '烤全羊'],
            classify_id: 3
          },
          {
            id: 2,
            icon: 'https://thirdwx.qlogo.cn/mmopen/giaZ5wiazUJx4A4qjNAVSvm52xqo7bnWdbrtf6qnX6qzfSE4l3VE4CIBH44MdIUOtUhRsia5aETTRic8Z1GcHZrTnSR4SEGXxuAx/132',
            lat: '36.081326',
            lng: '111.578350',
            name: 'stall High',
            time: '早10:00 - 晚11:00',
            address: '门店地址门店地址门店地址',
            scope: ['烧烤', '烤全羊'],
            classify_id: 4
          }
        ],
        // 门店||地摊坐标的
        stall_markers: [],
        // 操作的标记下标
        marker_index: -1
      }
    },
    components: {
      roof
    },
    computed: {
      // 设备信息
      systemInfo () {
        return store.state.systemInfo
      },
      // 胶囊位置信息
      capsulePosition () {
        return store.state.capsule
      }
    },
    mounted () {
      QQMap = new QQMapWX({
        key: 'UTLBZ-VVMWK-LNSJD-AVNNK-PTTJT-JFBHP'
      })
      this.setContentPaddingTop()
      this.setMapHeight()
      mpvue.getLocation({
        type: 'gcj02',
        complete: (res) => {
          this.map.lng = res.longitude
          this.map.lat = res.latitude
        }
      })
      this.downToLocation()
        .then(() => {
          return this.createCanvas()
        })
        .then(() => {
          return this.imagesLoaded()
        })
        .then(() => {
          let data = []
          this.data.forEach((item, index) => {
            let iconPath = 'mapIcon/' + item.id + '.png'
            if (!File.exists(iconPath)) {
              iconPath = this.imageCircle(item.img, item.id)
            } else {
              iconPath = File.getDir() + iconPath
            }
            data.push({
              iconPath: iconPath,
              id: index,
              latitude: item.lat,
              longitude: item.lng,
              width: 40,
              height: 40,
              anchor: {x: 0.5, y: 0.5}
            })
          })
          this.stall_markers = data
        })
    },
    methods: {
      // Run
      /**
       * 设置内容区域的padding-top
       */
      setContentPaddingTop () {
        this.content_padding_top = this.systemInfo.statusBarHeight + (this.capsulePosition.height + ((this.capsulePosition.top - this.systemInfo.statusBarHeight) * 2))
      },
      /**
       * 设置地图高度
       */
      setMapHeight () {
        select('.radar')
          .then((res) => {
            select('#classify')
              .then((res1) => {
                this.map_height = res[0].height - this.content_padding_top - res1[0].height
              })
          })
      },
      /**
       * 创建canvas
       */
      createCanvas () {
        return new Promise((resolve) => {
          const query = mpvue.createSelectorQuery()
          query.select('#canvas')
            .fields({ node: true, size: true })
            .exec((res) => {
              this.canvas = res[0].node
              this.canvas.width = 118
              this.canvas.height = 118
              this.context = this.canvas.getContext('2d')
              resolve()
            })
        })
      },
      /**
       *下载服务器图片至本地
       */
      downToLocation () {
        return new Promise((resolve) => {
          this.data.forEach((item, index) => {
            mpvue.getImageInfo({
              src: item.icon,
              success: (res) => {
                this.data[index].icon = res.path
                if (this.data.length - 1 === index) {
                  resolve()
                }
              }
            })
          })
        })
      },
      /**
       *等待所有图片加载完成
       */
      imagesLoaded () {
        return new Promise((resolve) => {
          this.data.forEach((item, index) => {
            let img = this.canvas.createImage()
            img.src = item.icon
            img.onload = () => {
              this.data[index].img = img
              if (this.data.length - 1 >= index) {
                resolve()
              }
            }
          })
        })
      },
      /**
       * 正方形图片转换圆形图片
       */
      imageCircle (img, classifyId) {
        this.context.fillStyle = '#FFffff'
        this.context.beginPath()
        this.context.arc(55, 55, 55, 0, 2 * Math.PI)
        this.context.fill()
        this.context.beginPath()
        this.context.fillStyle = '#000000'
        this.context.arc(55, 55, 48, 0, 2 * Math.PI)
        this.context.fill()
        this.context.clip()
        this.context.drawImage(img, 0, 0, img.width, img.height, 0, 0, this.canvas.width, this.canvas.height)
        this.context.closePath()
        // 返回本地地址
        return File.write('mapIcon', this.canvas.toDataURL().replace(/^data:image\/\w+;base64,/, ''), 'base64', classifyId + '.png')
      },
      /**
       * 选中的canvas图片
      */
      imageSelectedCircle () {
        this.context.fillStyle = '#FFffff'
        this.context.beginPath()
        this.context.arc(55, 55, 55, 0, 2 * Math.PI)
        this.context.fill()
      },

      // Handle
      /**
       * 搜索
       * @param ev
       */
      sendSearch (ev) {
        console.log(ev.target.value)
      },
      /**
       * 点击标记点
       */
      clickMarker (ev) {
        // 标记点下标|||
        if (this.marker_index >= 0) {
          this.stall_markers[this.marker_index].width = 40
          this.stall_markers[this.marker_index].height = 40
        }
        this.marker_index = ev.target.markerId
        this.stall_markers[this.marker_index].width = 50
        this.stall_markers[this.marker_index].height = 50
      },
      /**
       *显示路线
       */
      showLine () {
        // 路线规划
        this.getPolyline()
          .then((points) => {
            this.polyline = [{
              points: points,
              color: '#7F24FF',
              width: 6,
              arrowLine: true,
              borderWidth: 5
            }]
          })
      },
      /**
       * 获取规划的路线经纬度
       */
      getPolyline () {
        let stall = this.data[this.marker_index]
        return new Promise((resolve) => {
          QQMap.direction({
            from: {
              longitude: this.map.lng,
              latitude: this.map.lat
            },
            to: {
              longitude: stall.lng,
              latitude: stall.lat
            },
            success: (result) => {
              let coords = result.result.routes[0].polyline
              for (let i = 2; i < coords.length; i++) {
                coords[i] = coords[i - 2] + coords[i] / 1000000
              }
              let polyline = []
              for (let i = 0; i < coords.length / 2; i++) {
                let position = {
                  latitude: coords[i * 2],
                  longitude: coords[i * 2 + 1]
                }
                polyline.push(position)
              }
              resolve(polyline)
            }
          })
        })
      }
    }
  }
</script>

<style scoped lang="less" src="./index.less"></style>
